package no.nordicsemi.android.toolbox.profile.data

import no.nordicsemi.android.toolbox.lib.utils.Profile
import no.nordicsemi.android.toolbox.profile.data.uart.UARTConfiguration
import no.nordicsemi.android.toolbox.profile.data.uart.UARTMacro

data class UARTServiceData(
    override val profile: Profile = Profile.UART,
    val messages: List<UARTRecord> = emptyList(),
    val command: String? = null,
    val maxWriteLength: Int = 20,
    val uartViewState: UARTViewState = UARTViewState(),
    val sensorData: UARTSensorData? = null  // 添加解析后的传感器数据
) : ProfileServiceData()

data class UARTRecord(
    val text: String,
    val type: UARTRecordType,
    val timestamp: Long = System.currentTimeMillis(),
    val rawData: ByteArray? = null  // 添加原始字节数据
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as UARTRecord
        if (text != other.text) return false
        if (type != other.type) return false
        if (timestamp != other.timestamp) return false
        if (rawData != null) {
            if (other.rawData == null) return false
            if (!rawData.contentEquals(other.rawData)) return false
        } else if (other.rawData != null) return false
        return true
    }

    override fun hashCode(): Int {
        var result = text.hashCode()
        result = 31 * result + type.hashCode()
        result = 31 * result + timestamp.hashCode()
        result = 31 * result + (rawData?.contentHashCode() ?: 0)
        return result
    }
}

// UART传感器数据结构（34字节数据帧：温度、压力、心率、血氧、血容量、阻抗、电量）
data class UARTSensorData(
    val temperature: Float = 0f,    // 温度
    val pressure: Float = 0f,       // 压力
    val heartRate: Int = 0,         // 心率
    val bloodOxygen: Int = 0,       // 血氧
    val bloodVolume: Float = 0f,    // 血容量
    val impedance: Float = 0f,      // 阻抗
    val battery: Int = 0,           // 电量
    val isValid: Boolean = false    // 数据是否有效（帧头帧尾校验）
)

enum class UARTRecordType {
    INPUT, OUTPUT
}

data class UARTViewState(
    val editedPosition: Int? = null,
    val selectedConfigurationName: String? = null,
    val isConfigurationEdited: Boolean = false,
    val configurations: List<UARTConfiguration> = emptyList(),
    val isInputVisible: Boolean = true
) {
    val showEditDialog: Boolean = editedPosition != null

    val selectedConfiguration: UARTConfiguration? =
        configurations.find { selectedConfigurationName == it.name }

    val selectedMacro: UARTMacro? = selectedConfiguration?.let { configuration ->
        editedPosition?.let {
            configuration.macros.getOrNull(it)
        }
    }
}